package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"math"
	"real-time-registration/models"
)

type RegistrationControllers struct {
	beego.Controller
}

type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *RegistrationControllers) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	phone := c.GetString("phone")
	departments := c.GetString("departments")
	costs, _ := c.GetFloat("costs", 0)
	headerImg, header, err := c.GetFile("headerimg")
	if name == "" || phone == "" || departments == "" {
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "请确保所有参数不为空",
			Data: nil,
		}
		_ = c.ServeJSON()
		return
	}
	if err != nil {
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "图片获取失败",
			Data: nil,
		}
		_ = c.ServeJSON()
		return
	}
	err = headerImg.Close()
	if err != nil {
		return
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("headerimg", path)
	if err != nil {
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "图片上传失败",
			Data: nil,
		}
		_ = c.ServeJSON()
		return
	}
	registration := models.Registration{
		Model:       gorm.Model{},
		Name:        name,
		Phone:       phone,
		Departments: departments,
		Costs:       costs,
		HeaderImg:   "http://127.0.0.1:8080/" + path,
	}
	err = models.DB.Create(&registration).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "添加失败",
			Data: nil,
		}
		_ = c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		_ = c.ServeJSON()
	}
}

func (c *RegistrationControllers) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	offset := (page - 1) * size
	var count int64
	models.DB.Model(&models.Registration{}).Count(&count)
	sum := int(math.Ceil(float64(count) / float64(size)))

	up := page - 1
	if up < 1 {
		up = page
	}
	down := page + 1
	if down > sum {
		down = page
	}

	var registration []models.Registration

	err := models.DB.Limit(size).Offset(offset).Find(&registration).Error

	if err != nil {
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "查询失败",
			Data: nil,
		}
		_ = c.ServeJSON()
		return
	} else {
		data := map[string]interface{}{
			"data": registration,
			"sum":  sum,
			"up":   up,
			"down": down,
		}
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: data,
		}
		_ = c.ServeJSON()
	}
}
